﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jhong.FunMVCBlog.Core.Infrastructure
{
    public class PageHelper
    {
        private int _pageIndex;

        private int _totalPageCount;

        public PageHelper(int pageIndex, int totalPageCount)
        {
            this._pageIndex = pageIndex;
            this._totalPageCount = totalPageCount;
        }

        public string GetPageHtml()
        {
            var sb = new StringBuilder();
            //left
            sb.Append("<div class='col-sm-6'>");
            sb.Append(string.Format("<div class='dataTables_info' id='dataTables-example_info' role='status' aria-live='polite'>当前第{0}页，共{1}页</div>", this._pageIndex, this._totalPageCount));
            sb.Append("</div>");
            //right
            sb.Append("<div class='col-sm-6'>");
            sb.Append("<div class='dataTables_paginate paging_simple_numbers' id='dataTables-example_paginate'>");
            sb.Append("<ul class='pagination'>");

            int left, right;
            if (this._totalPageCount <= 7)
            {
                left = 1;
                right = this._totalPageCount;
            }
            else
            {
                if (this._pageIndex < 4)
                {
                    left = 1;
                    right = 7;
                }
                else if (this._pageIndex > this._totalPageCount - 4)
                {
                    right = this._totalPageCount;
                    left = right - 7;
                }
                else
                {
                    left = this._pageIndex - 3;
                    right = this._pageIndex + 3;
                }
            }
            if (left != right)
            {
                for (int i = left; i <= right; i++)
                {
                    sb.Append(string.Format("<li class='paginate_button{1}' aria-controls='dataTables-example' tabindex='0'><a href='###' {1} >{0}</a></li>", i, i == this._pageIndex ? " active" : string.Empty));
                }
            }

            sb.Append("</ul>");
            sb.Append("</div>");
            sb.Append("</div>");


            return sb.ToString();
        }
    }

    public static class PageContainerExtension
    {
        public static PageHelper GetPageHelper<T>(this PageContainer<T> container)
        {
            return new PageHelper(container.PageIndex, container.TotalPage);
        }
    }
}
